package com.zzw.zim.security.event;

import com.zzw.zim.common.constant.Constant;
import com.zzw.zim.system.enums.LoginOperationEnum;
import com.zzw.zim.system.service.SysLogLoginService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 认证事件处理，认证事件处理 登录日志存储

 * @author XiaoJie
 * @date 2025/06/03 10:21:10
 */
@Component
@AllArgsConstructor
public class AuthenticationEvents {

	private final SysLogLoginService sysLogLoginService;

	/**
	 * 登录成功日志保存
	 *
	 * @param event
	 */
	@EventListener
	public void onSuccess (AuthenticationSuccessEvent event) {
		// 用户信息
		UserDetails user = (UserDetails) event.getAuthentication().getPrincipal();
		// 保存登录日志
		sysLogLoginService.save(user.getUsername(), Constant.SUCCESS, LoginOperationEnum.LOGIN_SUCCESS.getValue());
	}

	/**
	 * 登录失败日志保存
	 *
	 * @param event
	 */
	@EventListener
	public void onFailure (AbstractAuthenticationFailureEvent event) {
		// 用户名
		String username = (String) event.getAuthentication().getPrincipal();
		// 保存登录日志
		sysLogLoginService.save(username, Constant.FAIL, LoginOperationEnum.ACCOUNT_FAIL.getValue());
	}
}
